import pygame
import sys
import time
import random
from point import *
from pygame.locals import *

    
 
pygame.init()

pygame.display.set_caption('')
#screen = pygame.display.set_mode( (800,400), pygame.FULLSCREEN )
screen = pygame.display.set_mode( (800,400) )



def initial_snake():
    head = Point()
    head.y = 200
    head.x = 500
    head.dir = POINT_RIGHT
    
    
    tail = Point()
    tail.x = 400
    tail.y = 200
    tail.dir = POINT_RIGHT
    return [tail,head]

point_list = initial_snake()
food = []

def add_new_food(food):
    new_food = Point(random.randint(10,790),random.randint(10,390))
    new_food.x = new_food.x - new_food.x % 10;
    new_food.y = new_food.y - new_food.y % 10; 
    food.append(new_food)
    
add_new_food(food)


def refresh( points,food ):
    pygame.draw.lines( screen, (255,255,255), False, points, 10 )
    for f in food:
        pygame.draw.rect( screen, (0,255,0), (f.x - 4, f.y - 4, 10,10 ))
    pygame.display.update()

def to_pairs( input ):
    output = []
    for i in input:
        output.append((i.x, i.y))
    return output

def detect_collision(point_list):
    head = point_list[-1]
    if ( head in point_list[:-1] ): 
        return True 
    
    for i in range(0 , len(point_list) - 2 ):
        pi = point_list[i]
        pnext = point_list[i+1]

        if ( head.y == pi.y == pnext.y or head.x == pi.x == pnext.x ) and  ( pi <= head <= pnext or pnext <= head <= pi ) :
            return True
    
    return False 
            
        
        
        
while True:
    screen.fill((125,0,125))
    head = point_list[-1]
    tail = point_list[0]
    for event in pygame.event.get():
        if event.type == KEYDOWN:            
            if event.key == K_ESCAPE:
                sys.exit()
            if ( head.change_dir( event.key ) ):
                old_head = head
                head = Point()
                head.x = old_head.x
                head.y = old_head.y
                head.dir = old_head.dir                
                point_list.append( head )
                
    if not ((0 < head.x  < 800 and  0 < head.y < 400)):
        point_list = initial_snake()
        screen.fill((125,0,125))
        
                            
    time.sleep(0.06)
    head.move(10)
    tail.move(10)
    
    if tail == point_list[1]:
        point_list.remove(tail)
    
    if ( head in food ):
        food = []
        add_new_food(food)
    
    if ( detect_collision(point_list) ):
        point_list = initial_snake()
        screen.fill((125,0,125))
        
    refresh( to_pairs(point_list), food )
            
   
        
